//将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
//
// 
//
// 示例： 
//
// 输入：1->2->4, 1->3->4
//输出：1->1->2->3->4->4
// 
// Related Topics 链表 
// 👍 1212 👎 0

package leetcode.editor.cn;

//Java：合并两个有序链表
public class P21MergeTwoSortedLists {


    /*
    *
    * 思路: 类似双指针，两个指针在两个链表遍历，小的输出，右移，直到两个都为链表尽头
    *
    * 执行用时： 1 ms , 在所有 Java 提交中击败了 63.27% 的用户 内存消耗： 39.7 MB , 在所有 Java 提交中击败了 10.25% 的用户
    * */
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode node = new ListNode();
            ListNode last = node;

            while (l1 != null || l2 != null) {
                if (l1 == null) {
                    ListNode temp = new ListNode(l2.val);
                    last.next = temp;
                    last = temp;
                    l2 = l2.next;
                } else if (l2 == null) {
                    ListNode temp = new ListNode(l1.val);
                    last.next = temp;
                    last = temp;
                    l1 = l1.next;
                } else {
                    if (l1.val <= l2.val) {
                        ListNode temp = new ListNode(l1.val);
                        last.next = temp;
                        last = temp;
                        l1 = l1.next;
                    } else {
                        ListNode temp = new ListNode(l2.val);
                        last.next = temp;
                        last = temp;
                        l2 = l2.next;
                    }
                }
            }
            return node.next;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)

    public static void main(String[] args) {
        Solution solution = new P21MergeTwoSortedLists().new Solution();
        ListNode node1 = new ListNode(4);
        node1 = add(node1, 2);
        node1 = add(node1, 1);

        ListNode node2 = new ListNode(4);
        node2 = add(node2, 3);
        node2 = add(node2, 1);

        ListNode node = solution.mergeTwoLists(node1, node2);
        System.out.println(node);
        // TO TEST
    }

    private static ListNode add(ListNode listNode, int x) {
        ListNode node = new ListNode(x);
        node.next = listNode;
        return node;
    }

}